<?php

namespace App\Http\Controllers\Web\User;

use App\Repository\Repositories\Interfaces\CompanyRepository;
use App\Repository\Repositories\Interfaces\CompanyMaterialRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Repositories\Interfaces\UserRepository;
use App\Repository\Repositories\Interfaces\UserLogRepository;
use App\ConstDir\ErrorConst;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Facades\JWTFactory;

use App\Repository\Repositories\Interfaces\UserImRepository;


class UserController extends BaseController
{

    protected $user_repo;
    protected $user_im;

    protected $api_url = [
        'createIm' => ['post', 'user/create.action'],
        'update' => ['post', '/user/updateUinfo.action'], // 更新用户信息 accid name icon sign email birth mobile gender ex
    ];
    public function __construct(UserRepository $user_repo,UserImRepository $user_im)
    {
        $this->user_repo = $user_repo;
        $this->user_im = $user_im;

    }


    /**
     * 用户手机号验证
     * @param Request $request
     *
     */
    public function checkphone(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required|string|min:11|max:11',
        ]);
        $phone = $request->input('phone');
        $data = $this->user_repo->checkPhone($phone);

        if(empty($data)){
            return $this->success(ErrorConst::PHONE_CHECK_NO_MSG,ErrorConst::PHONE_CHECK_NO_CODE);
        }

        if($data['status'] != 0) {
            return $this->success(ErrorConst::PHONE_ERROR_STATUS_MSG, ErrorConst::PHONE_ERROR_STATUS_CODE);
        }else {
            return $this->success(ErrorConst::PHONE_CHECK_YES_MSG, ErrorConst::PHONE_CHECK_YES_CODE);
        }


    }


    /**
     * 用户名验证
     * @param Request $request
     *
     */
    public function checkUserName(Request $request)
    {
        $this->validate($request, [
            'organization_code' => 'required|string',
        ]);
        $user_name = $request->input('organization_code');
        $data = $this->user_repo->checkUserName($user_name);

        if(empty($data)){
            return $this->success(ErrorConst::NAME_CHECK_NO_MSG,ErrorConst::PHONE_CHECK_NO_CODE);
        }

        if($data['status'] != 0) {
            return $this->success(ErrorConst::NAME_ERROR_STATUS_MSG, ErrorConst::PHONE_ERROR_STATUS_CODE);
        }else {
            return $this->success(ErrorConst::NAME_CHECK_YES_MSG, ErrorConst::PHONE_CHECK_YES_CODE);
        }


    }

    
    public function checkPayPwd(Request $request)
    {
        $this->validate($request, [
            'pay_pwd' => 'required|string',
            'id'=>'required|integer',
        ]);
        $pay_pwd = $request->input('pay_pwd');
        $id = $request->input('id');
       
        $ret = $this->user_repo->checkPayPwd($id,$pay_pwd);
         
        if($ret){
            return $this->success(ErrorConst::SUCCESS_CODE, $ret);
        }else{
            return $this->error(ErrorConst::ERROR_CODE);
        }
        
        
        
    }
    
    public function getLastLogin(UserLogRepository $user_log,Request $request){
        $this->validate($request, [
            'user_id'=>'required|integer',
        ]);
        $user_id = $request->input('user_id');
        
        $ret = $user_log->getLastLogin($user_id);
        $data = "";
        if(isset($ret[1]['created_at'])){
            $data = $ret[1]['created_at'];
        }
        
        if(isset($ret[0]['created_at'])){
            $data = $ret[0]['created_at'];
        }
        
        if($data){
            return $this->success(ErrorConst::SUCCESS_CODE, $data);
        }else{
            return $this->error(ErrorConst::ERROR_CODE);
        }
    }


    public function login(UserLogRepository $user_log,Request $request)
    {
        $this->validate($request, [
            'username' => 'required|string',
            'pwd' => 'required|string',
            'logn_equipment'=>'string',
            'ip'=>'string',
        ]);
        $data = $request->all('username','pwd','ip','logn_equipment');

       $userinfo = $this->user_repo->checkUserLogin($data['username'],md5($data['pwd']));

       if(empty($userinfo)){
           return $this->error(ErrorConst::LOGIN_ERROR_MSG,ErrorConst::LOGIN_ERROR_CODE);
       }

        if($userinfo['status'] == 0){

           try {
               $customClaims = ['iss' => JWTFactory::iss(), 'iat' => JWTFactory::iat(), 'exp' => JWTFactory::exp(),
                   'nbf' => JWTFactory::nbf(), 'sub' => $userinfo['id'], 'jti' => \Illuminate\Support\Str::random(), 'scope' => 'web'];
               $payload = JWTFactory::make($customClaims);
               $token = \JWTAuth::encode($payload)->get();

               //入库登陆记录
               $data_log = [
                   'user_id'=>$userinfo['id'],
                   'ip'=>isset($data['ip']) ? $data['ip'] : '',
                   'logn_equipment'=>isset($data['logn_equipment']) ? $data['logn_equipment'] : ''
               ];
               $user_log->create($data_log);
               $userinfo['user_token'] = $token;
               return $this->success(ErrorConst::SUCCESS_CODE, $userinfo);

           }catch (JWTException $e){
               return $this->error(ErrorConst::JWT_TOKEN_CREATE_MSG,ErrorConst::JWT_TOKEN_CREATE_CODE);
           }

        }else {
            return $this->error(ErrorConst::LOGIN_ERROR_STATUS_MSG,ErrorConst::LOGIN_ERROR_STATUS_CODE);
        }

    }



    /*
    *
    * 通过短信直接登录
    */
    public function messagesLogin(UserLogRepository $user_log,Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'key' => 'required|string',
            'logn_equipment'=>'string',
            'ip'=>'string',
            'code' => 'required|string',
        ]);

        $data = $request->all();

        $code = \Cache::get($data['username']);
        if(!$code){
            return $this->error(ErrorConst::SMS_CODE_NO_MSG,ErrorConst::SMS_CODE_NO_CODE);
        }
        if($code != $data['code']){
            return $this->error(ErrorConst::SMS_CODE_ERROR_MSG,ErrorConst::SMS_CODE_ERROR_CODE);
        }

        $userinfo = $this->user_repo->checkPhone($data['username']);
        if(empty($userinfo)){
            return $this->error(ErrorConst::PHONE_CHECK_NO_MSG,ErrorConst::PHONE_CHECK_NO_CODE);
        }

        if($userinfo['status'] != 0){
            return $this->error(ErrorConst::LOGIN_ERROR_STATUS_MSG,ErrorConst::LOGIN_ERROR_STATUS_CODE);
        }

        $sms_login_key = config('securitysetting.sms_login_key');

        if (md5($sms_login_key) == $data['key']) {

            try {
                $customClaims = ['iss' => JWTFactory::iss(), 'iat' => JWTFactory::iat(), 'exp' => JWTFactory::exp(),
                    'nbf' => JWTFactory::nbf(), 'sub' => $userinfo['id'], 'jti' => \Illuminate\Support\Str::random(), 'scope' => 'web'];
                $payload = JWTFactory::make($customClaims);
                $token = \JWTAuth::encode($payload)->get();

                //入库登陆记录
                $data_log = [
                    'user_id'=>$userinfo['id'],
                    'ip'=>isset($data['ip']) ? $data['ip'] : '',
                    'logn_equipment'=>isset($data['logn_equipment']) ? $data['logn_equipment'] : ''
                ];
                $user_log->create($data_log);
                $userinfo['user_token'] = $token;
                return $this->success(ErrorConst::SUCCESS_CODE, $userinfo);

            }catch (JWTException $e){
                return $this->error(ErrorConst::JWT_TOKEN_CREATE_MSG,ErrorConst::JWT_TOKEN_CREATE_CODE);
            }

        } else {
            return $this->error(ErrorConst::BASE_ERROR_MSG,ErrorConst::BASE_ERROR);
        }
    }





    /*
     * 找回密码
     */
   public function backPwd(UserLogRepository $user_log,Request $request)
    {

        $this->validate($request, [
            'phone' => 'required',
            'logn_equipment'=>'string',
            'ip'=>'string',
            'key' => 'required|string',
            'pwd' => 'required',
        ]);
        $data = $request->all('phone','key','pwd','ip','logn_equipment');

        $back_key = config('securitysetting.sms_login_key');

        if (md5($back_key) != $data['key']) {
            return $this->error(ErrorConst::BASE_ERROR_MSG,ErrorConst::BASE_ERROR);
        }

        //查询相应用户是否存在
        $userinfo = $this->user_repo->checkPhone($data['phone']);

        if(empty($userinfo)){
            return $this->error(ErrorConst::PHONE_CHECK_NO_MSG,ErrorConst::PHONE_CHECK_NO_CODE);
        }

        if($userinfo['status'] != 0){
            return $this->error(ErrorConst::LOGIN_ERROR_STATUS_MSG,ErrorConst::LOGIN_ERROR_STATUS_CODE);
        }

        $value = ['pwd' => md5($data['pwd'])];

        $ret = $this->user_repo->update($value, $userinfo['id']);
        //找回密码记录入库
        $data_log = [
            'user_id'=>$userinfo['id'],
            'insert_type'=>2,
            'ip'=>isset($data['ip']) ? $data['ip'] : '',
            'logn_equipment'=>isset($data['logn_equipment']) ? $data['logn_equipment'] : ''
        ];
        $user_log->create($data_log);

        if ($ret) {
            return $this->success(ErrorConst::SUCCESS_CODE_MSG, ErrorConst::SUCCESS_CODE);
        } else {
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
    }



    /*
     * 新版企业注册
     */

    public function companyRegisterNew(CompanyRepository $company_repo,CompanyMaterialRepository $companymaterial_repo,Request $request)
    {

        $this->validate($request, [
            'company_name' => 'required|string',
            'ent_type' => 'required|json',
            'phone' => 'required|string',
            'pwd' => 'required|string',
            'organization_code' => 'required|string'
        ]);

        $data = $request->all();

        //查询相应用户是否存在
        $userinfo = $this->user_repo->checkPhone($data['phone']);

        if(!empty($userinfo)){
            return $this->error(ErrorConst::PHONE_CHECK_YES_MSG,ErrorConst::PHONE_CHECK_YES_CODE);
        }

        \DB::beginTransaction();
        try {
            //user入库
            $data_user = [
                'name' => $data['phone'],//$data['organization_code'],
                'phone' => $data['phone'],
                'pwd' => md5($data['pwd']),
                'personal_enterprise' => 1,
            ];
            $user_create = $this->user_repo->create($data_user);

            //company入库
            $data_company = [
                'user_id' => $user_create['data']['id'],
                'company_name' => $data['company_name'],
                'company_address' =>$data['company_address'],
                'organization_code' => $data['organization_code']
            ];

            $company_create = $company_repo->create($data_company);

            //company_material入库
            $data_companymaterial = [
                'user_id' => $user_create['data']['id'],
                'company_id' => $company_create['data']['id'],
                'ent_type' => $data['ent_type']
            ];

            $companymaterial_repo->create($data_companymaterial);

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }

        return $this->success(ErrorConst::SUCCESS_CODE_MSG);



    }







    /*
     * 企业注册
     */

    public function companyRegister(CompanyRepository $company_repo,CompanyMaterialRepository $companymaterial_repo,Request $request)
    {

        $this->validate($request, [
            'company_name' => 'required|string',
            'ent_type' => 'required|json',
            //'business_trade' => 'required|json',
            //'business_product' => 'required|sometimes|json',
            'contact_person' => 'required|string',
            //'contact_sex' => 'required|integer|in:1,0',
            'phone' => 'required|string',
            'code' => 'required|string',
            'pwd' => 'required|string',
            'organization_code' => 'required|string'
        ]);

        $data = $request->all();

        //查询相应用户是否存在
        $userinfo = $this->user_repo->checkPhone($data['phone']);

        if(!empty($userinfo)){
            return $this->error(ErrorConst::PHONE_CHECK_YES_MSG,ErrorConst::PHONE_CHECK_YES_CODE);
        }

        //验证手机验证码
        $code = \Cache::get($data['phone']);
        if(!$code){
            return $this->error(ErrorConst::SMS_CODE_NO_MSG,ErrorConst::SMS_CODE_NO_CODE);
        }

        if($code != $data['code']){
            return $this->error(ErrorConst::SMS_CODE_ERROR_MSG,ErrorConst::SMS_CODE_ERROR_CODE);
        }


        /*//邀请人查询
        $inviter_phone = !empty($data['inviter']) ? $data['inviter'] : '';
        $inviterinfo = $this->user_repo->checkPhone($inviter_phone);
        $inviter_id = 0;
        if(!empty($inviterinfo) and !empty($inviterinfo['phone'])){
            $inviter_id = $inviterinfo['id'];
        }*/

        \DB::beginTransaction();
        try {
            //user入库
            $data_user = [
                'name' => $data['phone'],//$data['organization_code'],
                'phone' => $data['phone'],
                'pwd' => md5($data['pwd']),
                //'inviter_id' => $inviter_id,
                'personal_enterprise' => 1,
            ];
            $user_create = $this->user_repo->create($data_user);

            //company入库
            $data_company = [
                'user_id' => $user_create['data']['id'],
                'company_name' => $data['company_name'],
                'licence_type' =>$data['licence_type'],
                'agnet_licence' =>$data['agnet_licence'],
                'tax_certificate' =>$data['tax_certificate'],
                'organization_code_certificate' =>$data['organization_code_certificate'],
                'organization_code' => $data['organization_code'],
                'company_tel' => $data['company_tel']
            ];

            $company_create = $company_repo->create($data_company);

            //company_material入库
            $data_companymaterial = [
                'user_id' => $user_create['data']['id'],
                'company_id' => $company_create['data']['id'],
                'ent_type' => $data['ent_type'],
                //'business_trade' => $data['business_trade'],
                //'business_product' => $data['business_product'],
                'contact_person' => $data['contact_person'],
                //'contact_sex' => $data['contact_sex'],
                'contact_mobile' => $data['phone'],
            ];

            $companymaterial_repo->create($data_companymaterial);

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }

        return $this->success(ErrorConst::SUCCESS_CODE_MSG);



    }





    /*
     * 个人注册
     */

    public function personalRegister(Request $request)
    {

        $this->validate($request, [
            'phone' => 'required|string',
            'name' => 'required|string',
            'pwd' => 'required|string',
            'code' => 'required|string',
        ]);

        $data = $request->all();

        //查询相应用户是否存在
        $userinfo = $this->user_repo->checkPhone($data['phone']);

        if(!empty($userinfo)){
            return $this->error(ErrorConst::PHONE_CHECK_YES_MSG,ErrorConst::PHONE_CHECK_YES_CODE);
        }

        //验证手机验证码
        $code = \Cache::get($data['phone']);
        if(!$code){
            return $this->error(ErrorConst::SMS_CODE_NO_MSG,ErrorConst::SMS_CODE_NO_CODE);
        }

        if($code != $data['code']){
            return $this->error(ErrorConst::SMS_CODE_ERROR_MSG,ErrorConst::SMS_CODE_ERROR_CODE);
        }


        //邀请人查询
        $inviter_phone = !empty($data['inviter']) ? $data['inviter'] : '';
        $inviterinfo = $this->user_repo->checkPhone($inviter_phone);
        $inviter_id = 0;
        if(!empty($inviterinfo) and !empty($inviterinfo['phone'])){
            $inviter_id = $inviterinfo['id'];
        }

        \DB::beginTransaction();
        try {
            //user入库
            $data_user = [
                'name' => $data['name'],
                'phone' => $data['phone'],
                'pwd' => md5($data['pwd']),
                'inviter_id' => $inviter_id,
                'personal_enterprise' => 0,
            ];

            $this->user_repo->create($data_user);

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }

        return $this->success(ErrorConst::SUCCESS_CODE_MSG);



    }
    /**
     * 验证是否有 IM 账号
     * */
    public function verify_im(Request $request){

        $this->validate($request, [
            'user_id' => 'required',
        ]);
        try {
            $user_id = $request->get('user_id');
            // 检测数据库是否有该用户的IM 账号。
            $imInfo = $this->user_im->with(['company','user'])->findWhere(['user_id' => $request->get('user_id')]);
            $userInfo = $this->user_repo->find($user_id);
            $userInfo = $userInfo['data'];
            $name = isset($imInfo['data'][0]['company']['company_name'])?$imInfo['data'][0]['company']['company_name']:$userInfo['name'];

            $password = $request->get('password','123456');
            // 如果数据库无该用户IM 账号，即创建IM 账号并关联。
            $data = [
                'accid' => 'aoce_' . $user_id,
                'name' => $name,
                'password' => $password,
            ];
            if (count($imInfo['data']) <= 0){
                // IM 创建用户
                $imCreate = http_im($this->api_url['createIm'])->send($data);

                if ($imCreate['code'] != 200) {
                    return $this->error('注册失败', $imCreate['code']);
                }
                $imCreate['info']['user_id'] = $user_id;
                $imCreate['info']['password'] = md5($data['password']);
            }else{
                // IM 修改用户信息
                $update = [
                    'accid'=>$imInfo['data'][0]['accid'],
                    'name'=>$name,
                    'icon'=>$imInfo['data'][0]['user']['pic'],
                ];
                $imUpdate = http_im($this->api_url['update'])->send($update);

                $imCreate['info']['accid'] = $imInfo['data'][0]['accid'];
                $imCreate['info']['name']  = $name;
                $imCreate['info']['user_id'] = $user_id;
                $imCreate['info']['password'] = md5($data['password']);
            }

            // 本地数据库存储
            $create = $this->user_im->updateOrCreate(['user_id'=>$user_id],$imCreate['info']);

        }catch (\Exception $e){
            return $this->error($e->getMessage());
            //Logger_custom('ERROR----' . var_export($e->getMessage(), 1), 'ecclub');
        }
        return $this->success(ErrorConst::SUCCESS_CODE_MSG,$create);
    }




}
